<template>
  <div class="page-container">
    <!-- Main Content -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 购买价格配置 -->
        <el-col :span="16">
          <el-card shadow="hover">
            <template #header>
              <div style="display: flex; align-items: center; justify-content: space-between;">
                <span style="font-size: 16px; font-weight: 600;">Purchase Price Configuration</span>
                <el-tag type="info">
                  Current: "{{ currentPriceInfo }}"
                </el-tag>
              </div>
            </template>

            <div style="margin-bottom: 20px;">
              <el-alert
                title="Configuration Guide"
                type="info"
                description="Configure the purchase price information displayed on the user recharge page. This text is shown below the title to indicate the exchange rate. Maximum 50 characters allowed."
                show-icon
                :closable="false"
                style="margin-bottom: 20px;"
              />
            </div>

            <!-- 当前价格信息显示 -->
            <div class="current-price-section">
              <h4>Current Price Info:</h4>
              <div class="price-preview">
                <el-tag
                  size="large"
                  type="warning"
                  style="margin: 4px 8px 4px 0; padding: 8px 16px;"
                >
                  Purchase Price: {{ currentPriceInfo }}
                </el-tag>
              </div>
            </div>

            <!-- 修改价格信息 -->
            <div class="edit-price-section">
              <h4>Update Price Info:</h4>
              <el-form
                ref="priceFormRef"
                :model="priceForm"
                :rules="priceRules"
                :inline="true"
              >
                <el-form-item prop="newPriceInfo">
                  <el-input
                    v-model="priceForm.newPriceInfo"
                    placeholder="Enter new price info"
                    size="large"
                    style="width: 250px;"
                    maxlength="50"
                    show-word-limit
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    size="large"
                    @click="updatePriceInfo"
                    :loading="updating"
                    :disabled="!priceForm.newPriceInfo || priceForm.newPriceInfo.trim() === currentPriceInfo"
                  >
                    <el-icon><Edit /></el-icon>
                    Update
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 预设价格信息 -->
            <div class="preset-prices-section">
              <h4>Quick Select Preset Prices:</h4>
              <div class="preset-prices">
                <el-button
                  v-for="preset in presetPrices"
                  :key="`preset-${preset}`"
                  size="small"
                  @click="selectPresetPrice(preset)"
                  :disabled="preset === currentPriceInfo"
                  style="margin: 4px 8px 4px 0;"
                >
                  {{ preset }}
                </el-button>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button
                size="large"
                @click="loadCurrentPriceInfo"
                :loading="loading"
              >
                <el-icon><Refresh /></el-icon>
                Refresh
              </el-button>
              <el-button
                type="success"
                size="large"
                @click="resetToDefault"
                :loading="updating"
              >
                <el-icon><RefreshLeft /></el-icon>
                Reset to Default
              </el-button>
            </div>
          </el-card>
        </el-col>

        <!-- 预览和帮助 -->
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <span style="font-size: 16px; font-weight: 600;">Preview & Help</span>
            </template>

            <!-- 预览效果 -->
            <div class="preview-section">
              <h4>Display Preview:</h4>
              <div class="display-preview">
                <div class="preview-title">Buy Coins</div>
                <div class="preview-price">Purchase Price: {{ priceForm.newPriceInfo || currentPriceInfo }}</div>
                <div class="preview-tips">Please select the amount of coins you want to purchase</div>
              </div>
            </div>

            <!-- 使用说明 -->
            <div class="help-section">
              <h4>Usage Notes:</h4>
              <ul class="help-list">
                <li>Maximum 50 characters allowed</li>
                <li>Changes take effect immediately</li>
                <li>Displayed on user recharge page</li>
                <li>Should indicate exchange rate clearly</li>
                <li>Common formats: "5.5THB=1M", "1USD=100Coins"</li>
                <li>Include currency and game currency units</li>
              </ul>
            </div>

            <!-- 价格格式建议 -->
            <div class="format-section">
              <h4>Format Examples:</h4>
              <ul class="format-list">
                <li><code>5.5泰铢=1M金币</code></li>
                <li><code>1USD=100Coins</code></li>
                <li><code>10CNY=200Diamonds</code></li>
                <li><code>0.1EUR=10Vouchers</code></li>
              </ul>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Edit, Refresh, RefreshLeft } from '@element-plus/icons-vue'
import { trpc } from '../utils/trpc'

// 响应式数据
const loading = ref(false)
const updating = ref(false)
const currentPriceInfo = ref('5.5泰铢=1M金币')
const priceFormRef = ref<FormInstance>()

// 表单数据
const priceForm = ref({
  newPriceInfo: ''
})

// 预设价格信息选项
const presetPrices = ref([
  '5.5泰铢=1M金币',
  '5.5THB=1M金币',
  '1USD=100Coins',
  '10CNY=200Diamonds',
  '0.1EUR=10Vouchers',
  '100JPY=50Diamonds'
])

// 表单验证规则
const priceRules: FormRules = {
  newPriceInfo: [
    { required: true, message: 'Please enter price info', trigger: 'blur' },
    { min: 1, max: 50, message: 'Price info length should be 1-50 characters', trigger: 'blur' }
  ]
}

// 加载当前价格信息
async function loadCurrentPriceInfo() {
  try {
    loading.value = true
    const result = await trpc.admin.getPurchasePriceInfo.query()
    
    if (result.success) {
      currentPriceInfo.value = result.data.priceInfo
      priceForm.value.newPriceInfo = result.data.priceInfo
      ElMessage.success('Current price info loaded successfully')
    } else {
      ElMessage.error(result.message || 'Failed to load current price info')
    }
  } catch (error) {
    console.error('Failed to load current price info:', error)
    ElMessage.error('Failed to load current price info')
  } finally {
    loading.value = false
  }
}

// 更新价格信息
async function updatePriceInfo() {
  if (!priceFormRef.value) return
  
  try {
    await priceFormRef.value.validate()
    
    const newPriceInfo = priceForm.value.newPriceInfo.trim()
    if (newPriceInfo === currentPriceInfo.value) {
      ElMessage.warning('Price info is the same as current one')
      return
    }
    
    updating.value = true
    const result = await trpc.admin.updatePurchasePriceInfo.mutate({
      priceInfo: newPriceInfo
    })
    
    if (result.success) {
      currentPriceInfo.value = result.data.priceInfo
      priceForm.value.newPriceInfo = result.data.priceInfo
      ElMessage.success('Purchase price info updated successfully')
    } else {
      ElMessage.error(result.message || 'Failed to update price info')
    }
  } catch (error) {
    console.error('Failed to update price info:', error)
    ElMessage.error('Failed to update price info')
  } finally {
    updating.value = false
  }
}

// 选择预设价格信息
function selectPresetPrice(preset: string) {
  priceForm.value.newPriceInfo = preset
}

// 重置为默认值
async function resetToDefault() {
  try {
    await ElMessageBox.confirm(
      'Are you sure you want to reset the price info to default ("5.5泰铢=1M金币")?',
      'Confirm Reset',
      {
        confirmButtonText: 'Reset',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
    )
    
    priceForm.value.newPriceInfo = '5.5泰铢=1M金币'
    await updatePriceInfo()
  } catch (error) {
    // User cancelled
  }
}

// 页面加载时获取当前配置
onMounted(() => {
  loadCurrentPriceInfo()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
}

.current-price-section,
.edit-price-section,
.preset-prices-section {
  margin-bottom: 24px;
}

.current-price-section h4,
.edit-price-section h4,
.preset-prices-section h4 {
  margin-bottom: 12px;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.price-preview {
  padding: 12px 0;
}

.preset-prices {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.action-buttons {
  margin-top: 32px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 12px;
}

.preview-section,
.help-section,
.format-section {
  margin-bottom: 24px;
}

.preview-section h4,
.help-section h4,
.format-section h4 {
  margin-bottom: 12px;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.display-preview {
  padding: 20px;
  background: #f9fafb;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.preview-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
  margin-bottom: 8px;
}

.preview-price {
  font-size: 13px;
  color: #f56c6c;
  font-weight: 500;
  margin-bottom: 4px;
}

.preview-tips {
  font-size: 12px;
  color: #6b7280;
  line-height: 1.4;
}

.help-list {
  padding-left: 20px;
  color: #6b7280;
  font-size: 13px;
  line-height: 1.6;
}

.help-list li {
  margin-bottom: 6px;
}

.format-list {
  padding-left: 20px;
  color: #6b7280;
  font-size: 13px;
  line-height: 1.6;
}

.format-list li {
  margin-bottom: 6px;
}

.format-list code {
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  color: #374151;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    max-width: 100%;
  }
}

@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }
  
  .el-col {
    margin-bottom: 20px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .preset-prices {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>